package com.yugao.fintech.libra.workflow.service.impl;

import com.yugao.fintech.draper.cache.constant.RedisKeyConstants;
import com.yugao.fintech.draper.cache.service.RedisService;
import com.yugao.fintech.libra.workflow.api.model.AuditConfig;
import com.yugao.fintech.libra.workflow.mapper.IAuditConfigMapper;
import com.yugao.fintech.libra.workflow.service.IAuditConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

@Service
public class AuditConfigServiceImpl implements IAuditConfigService {
    @Autowired
    private IAuditConfigMapper auditConfigMapper;
    @Autowired
    private RedisService redisService;
    
    @PostConstruct
    public void init() {
        loadCache();
    }

    @Override
    public List<AuditConfig> list(AuditConfig auditConfig) {
        return auditConfigMapper.list(auditConfig);
    }

    // 单个修改语句，取消事务
    @Override
    public int editStatus(AuditConfig auditConfig) {
        int res = auditConfigMapper.editStatus(auditConfig);
        // 状态修改，刷新缓存
        AuditConfig tempAuditConfig = auditConfigMapper.queryById(auditConfig.getId());
        redisService.setCacheObject(RedisKeyConstants.WORKFLOW_AUDIT_CONFIG + auditConfig.getCode(), tempAuditConfig);
        return res;
    }

    @Override
    public AuditConfig queryByCode(String code) {
        AuditConfig auditConfig = redisService.getCacheObject(RedisKeyConstants.WORKFLOW_AUDIT_CONFIG + code);
        if (Objects.isNull(auditConfig)) {
            auditConfig = auditConfigMapper.queryByCode(code);
            if (Objects.nonNull(auditConfig)) {
                redisService.setCacheObject(RedisKeyConstants.WORKFLOW_AUDIT_CONFIG + auditConfig.getCode(), auditConfig);
            }
        }
        return auditConfig;
    }

    @Override
    public void refreshCache() {
        clearCache();
        loadCache();
    }

    private void clearCache() {
        Collection<String> keys = redisService.keys(RedisKeyConstants.WORKFLOW_AUDIT_CONFIG + "*");
        redisService.deleteObject(keys);
    }

    private void loadCache() {
        List<AuditConfig> list = auditConfigMapper.list(new AuditConfig());
        list.forEach(auditConfig -> {
            redisService.setCacheObject(RedisKeyConstants.WORKFLOW_AUDIT_CONFIG + auditConfig.getCode(), auditConfig);
        });
    }

}
